package org.springframework.ai.mcp.server.demo.resources;

import io.modelcontextprotocol.server.McpServerFeatures;
import io.modelcontextprotocol.spec.McpSchema;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 系统资源配置类，提供系统信息和动态内容资源。
 * 
 * <p>此配置类演示了如何：
 * <ul>
 * <li>创建MCP资源规范</li>
 * <li>提供静态和动态资源</li>
 * <li>处理资源读取请求</li>
 * <li>返回不同类型的内容</li>
 * </ul>
 * 
 * @author Spring AI Team
 * @since 1.1.0
 */
@Configuration
public class SystemResourcesConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(SystemResourcesConfiguration.class);

	@Bean
	public List<McpServerFeatures.SyncResourceSpecification> syncResourceSpecifications(){
		return List.of(systemInfoResource(), currentTimeResource(), appStatusResource());
	}

    /**
     * 系统信息资源：提供JVM和系统的基本信息。
     */
	public McpServerFeatures.SyncResourceSpecification systemInfoResource() {
		// 构造资源描述
		McpSchema.Resource resource = new McpSchema.Resource(
				"system://info",
				"系统信息",
				"提供JVM和系统的基本信息",
				"text/plain",
				new McpSchema.Annotations(null, null)
		);

		return new McpServerFeatures.SyncResourceSpecification(
				resource,
				(exchange, request) -> {
					try {
						Runtime runtime = Runtime.getRuntime();

						String systemInfo = String.format(
								"=== 系统信息 ===\n" +
										"Java版本: %s\n" +
										"JVM名称: %s\n" +
										"JVM版本: %s\n" +
										"操作系统: %s %s\n" +
										"系统架构: %s\n" +
										"可用处理器: %d\n" +
										"最大内存: %d MB\n" +
										"总内存: %d MB\n" +
										"空闲内存: %d MB\n" +
										"已用内存: %d MB\n" +
										"当前时间: %s",
								System.getProperty("java.version"),
								System.getProperty("java.vm.name"),
								System.getProperty("java.vm.version"),
								System.getProperty("os.name"),
								System.getProperty("os.version"),
								System.getProperty("os.arch"),
								runtime.availableProcessors(),
								runtime.maxMemory() / 1024 / 1024,
								runtime.totalMemory() / 1024 / 1024,
								runtime.freeMemory() / 1024 / 1024,
								(runtime.totalMemory() - runtime.freeMemory()) / 1024 / 1024,
								LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
						);

						logger.info("提供系统信息资源");

						McpSchema.TextResourceContents contents = new McpSchema.TextResourceContents(
								request.uri(),
								"text/plain",
								systemInfo
						);

						return new McpSchema.ReadResourceResult(List.of(contents));
					} catch (Exception e) {
						logger.error("获取系统信息失败", e);

						McpSchema.TextResourceContents errorContents = new McpSchema.TextResourceContents(
								request.uri(),
								"text/plain",
								"错误：无法获取系统信息 - " + e.getMessage()
						);

						return new McpSchema.ReadResourceResult(List.of(errorContents));
					}
				}
		);
	}


	/**
     * 当前时间资源：提供实时的时间信息。
     */
	public McpServerFeatures.SyncResourceSpecification currentTimeResource() {
		// 构建资源元信息
		McpSchema.Resource resource = new McpSchema.Resource(
				"time://current",
				"当前时间",
				"提供当前的日期和时间信息",
				"application/json",
				new McpSchema.Annotations(List.of(), null)
		);

		return new McpServerFeatures.SyncResourceSpecification(
				resource,
				(exchange, request) -> {
					try {
						LocalDateTime now = LocalDateTime.now();

						String timeInfo = String.format(
								"{\n" +
										"  \"timestamp\": \"%s\",\n" +
										"  \"formatted\": \"%s\",\n" +
										"  \"year\": %d,\n" +
										"  \"month\": %d,\n" +
										"  \"day\": %d,\n" +
										"  \"hour\": %d,\n" +
										"  \"minute\": %d,\n" +
										"  \"second\": %d,\n" +
										"  \"dayOfWeek\": \"%s\",\n" +
										"  \"timezone\": \"%s\"\n" +
										"}",
								now.toString(),
								now.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss")),
								now.getYear(),
								now.getMonthValue(),
								now.getDayOfMonth(),
								now.getHour(),
								now.getMinute(),
								now.getSecond(),
								now.getDayOfWeek(),
								System.getProperty("user.timezone", "未知")
						);

						McpSchema.TextResourceContents contents = new McpSchema.TextResourceContents(
								request.uri(),
								"application/json",
								timeInfo
						);

						return new McpSchema.ReadResourceResult(List.of(contents));
					} catch (Exception e) {
						logger.error("获取当前时间失败", e);

						McpSchema.TextResourceContents errorContents = new McpSchema.TextResourceContents(
								request.uri(),
								"application/json",
								"{\"error\": \"无法获取当前时间: " + e.getMessage() + "\"}"
						);

						return new McpSchema.ReadResourceResult(List.of(errorContents));
					}
				}
		);
	}

	/**
     * 应用状态资源：提供应用程序的运行状态信息。
     */
	public McpServerFeatures.SyncResourceSpecification appStatusResource() {
		// 构造 Resource 元信息
		McpSchema.Resource resource = new McpSchema.Resource(
				"app://status",
				"应用状态",
				"提供Spring Boot应用程序的运行状态",
				"text/markdown",
				new McpSchema.Annotations(List.of(), null)
		);

		return new McpServerFeatures.SyncResourceSpecification(
				resource,
				(exchange, request) -> {
					try {
						Runtime runtime = Runtime.getRuntime();
						long usedMemory = (runtime.totalMemory() - runtime.freeMemory()) / 1024 / 1024;
						long freeMemory = runtime.freeMemory() / 1024 / 1024;
						long totalMemory = runtime.totalMemory() / 1024 / 1024;
						long uptimeMinutes = (System.currentTimeMillis() / 1000 / 60) % 60; // 简单近似

						String status = String.format(
								"# Spring AI MCP Server Demo 状态\n\n" +
										"## 基本信息\n" +
										"- **应用名称**: Spring AI MCP Server Demo\n" +
										"- **版本**: 1.1.0-SNAPSHOT\n" +
										"- **启动时间**: %s\n" +
										"- **运行时长**: %d 分钟\n\n" +
										"## 功能状态\n" +
										"- ✅ MCP服务器运行中\n" +
										"- ✅ 文本工具可用\n" +
										"- ✅ 系统资源可用\n\n" +
										"## 传输支持\n" +
										"- ✅ STDIO传输\n" +
										"- ✅ WebMVC SSE传输\n" +
										"- ✅ WebFlux SSE传输\n\n" +
										"## 内存使用\n" +
										"- **已用内存**: %d MB\n" +
										"- **空闲内存**: %d MB\n" +
										"- **总内存**: %d MB",
								LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")),
								uptimeMinutes,
								usedMemory,
								freeMemory,
								totalMemory
						);

						logger.info("提供应用状态资源");

						McpSchema.TextResourceContents contents = new McpSchema.TextResourceContents(
								request.uri(),
								"text/markdown",
								status
						);

						return new McpSchema.ReadResourceResult(List.of(contents));
					} catch (Exception e) {
						logger.error("获取应用状态失败", e);

						McpSchema.TextResourceContents errorContents = new McpSchema.TextResourceContents(
								request.uri(),
								"text/markdown",
								"# 错误\n\n无法获取应用状态: " + e.getMessage()
						);

						return new McpSchema.ReadResourceResult(List.of(errorContents));
					}
				}
		);
	}


}
